from pydantic import BaseModel, Field, validator
from typing import Optional


class InstagramInfoRequest(BaseModel):
    """获取Instagram媒体信息请求DTO"""
    instagram_url: str = Field(..., description="Instagram链接", min_length=1, max_length=2048)
    
    @validator('instagram_url')
    def validate_instagram_url(cls, v):
        """验证Instagram URL格式"""
        if not v or not v.strip():
            raise ValueError('Instagram链接不能为空')
        
        v = v.strip()
        
        # 简单的Instagram URL格式验证
        valid_domains = ['instagram.com', 'www.instagram.com', 'm.instagram.com']
        
        if not any(domain in v for domain in valid_domains):
            raise ValueError('请提供有效的Instagram链接')
        
        if not (v.startswith('http://') or v.startswith('https://')):
            raise ValueError('链接格式不正确，必须以http://或https://开头')
        
        # 检查是否包含媒体相关路径
        media_patterns = ['/p/', '/reel/', '/tv/', '/stories/']
        if not any(pattern in v for pattern in media_patterns):
            raise ValueError('链接必须包含媒体内容（/p/、/reel/、/tv/或/stories/）')
        
        return v


class InstagramUrlRequest(BaseModel):
    """获取Instagram下载链接请求DTO"""
    instagram_url: str = Field(..., description="Instagram链接", min_length=1, max_length=2048)
    quality: Optional[str] = Field("best", description="视频质量", max_length=10)
    
    @validator('instagram_url')
    def validate_instagram_url(cls, v):
        """验证Instagram URL格式"""
        if not v or not v.strip():
            raise ValueError('Instagram链接不能为空')
        
        v = v.strip()
        
        # 简单的Instagram URL格式验证
        valid_domains = ['instagram.com', 'www.instagram.com', 'm.instagram.com']
        
        if not any(domain in v for domain in valid_domains):
            raise ValueError('请提供有效的Instagram链接')
        
        if not (v.startswith('http://') or v.startswith('https://')):
            raise ValueError('链接格式不正确，必须以http://或https://开头')
        
        # 检查是否包含媒体相关路径
        media_patterns = ['/p/', '/reel/', '/tv/', '/stories/']
        if not any(pattern in v for pattern in media_patterns):
            raise ValueError('链接必须包含媒体内容（/p/、/reel/、/tv/或/stories/）')
        
        return v
    
    @validator('quality')
    def validate_quality(cls, v):
        """验证视频质量"""
        if v:
            valid_qualities = ['360p', '480p', '720p', '1080p', 'best', 'worst']
            if v.lower() not in [q.lower() for q in valid_qualities]:
                raise ValueError(f'无效的视频质量，支持的质量: {", ".join(valid_qualities)}')
            return v.lower()
        return "best"  # 默认最佳质量


class InstagramMultiQualityRequest(BaseModel):
    """获取Instagram多质量下载链接请求DTO"""
    instagram_url: str = Field(..., description="Instagram链接", min_length=1, max_length=2048)
    
    @validator('instagram_url')
    def validate_instagram_url(cls, v):
        """验证Instagram URL格式"""
        if not v or not v.strip():
            raise ValueError('Instagram链接不能为空')
        
        v = v.strip()
        
        # 简单的Instagram URL格式验证
        valid_domains = ['instagram.com', 'www.instagram.com', 'm.instagram.com']
        
        if not any(domain in v for domain in valid_domains):
            raise ValueError('请提供有效的Instagram链接')
        
        if not (v.startswith('http://') or v.startswith('https://')):
            raise ValueError('链接格式不正确，必须以http://或https://开头')
        
        # 检查是否包含媒体相关路径
        media_patterns = ['/p/', '/reel/', '/tv/', '/stories/']
        if not any(pattern in v for pattern in media_patterns):
            raise ValueError('链接必须包含媒体内容（/p/、/reel/、/tv/或/stories/）')
        
        return v


class InstagramUserMediaRequest(BaseModel):
    """获取Instagram用户媒体请求DTO"""
    username: str = Field(..., description="Instagram用户名", min_length=1, max_length=100)
    count: Optional[int] = Field(12, description="获取媒体数量", ge=1, le=50)
    
    @validator('username')
    def validate_username(cls, v):
        """验证Instagram用户名"""
        if not v or not v.strip():
            raise ValueError('用户名不能为空')
        
        v = v.strip()
        
        # 基本的用户名格式验证
        if len(v) < 1 or len(v) > 30:
            raise ValueError('用户名长度必须在1-30个字符之间')
        
        # 检查用户名是否包含非法字符（Instagram用户名只能包含字母数字下划线和点）
        import re
        if not re.match(r'^[a-zA-Z0-9._]+$', v):
            raise ValueError('用户名只能包含字母、数字、下划线和点')
        
        return v
    
    @validator('count')
    def validate_count(cls, v):
        """验证获取数量"""
        if v is not None:
            if v < 1 or v > 50:
                raise ValueError('获取数量必须在1-50之间')
        return v or 12 